//
//  HJPopMenuView.m
//  newOcWeibo
//
//  Created by heJing on 15/7/26.
//  Copyright © 2015年 heima. All rights reserved.
//

#import "HJPopMenuView.h"

UIWindow *_tempwindow;

MyBlock _dismiss;

UIViewController *_viewController;

@implementation HJPopMenuView


+ (void)popFrom:(UIView *)fromView content:(UIView *)contentView dismiss:(MyBlock)dismiss{

    // 5.显示菜单
     _tempwindow.hidden = NO;

    [self popFromRect:fromView.frame inView:fromView.superview content:contentView dismiss:dismiss];
}

+ (void)popFrom:(UIView *)fromView contentController:(UIViewController *)contentVC dismiss:(MyBlock)dismiss{
    _viewController = contentVC;
    [self popFromRect:fromView.frame inView:fromView.superview content:contentVC.view dismiss:dismiss];
}

+ (void)popFromRect:(CGRect)fromRect inView:(UIView *)inView content:(UIView *)contentView dismiss:(MyBlock)dismiss{
    // 0.保存block
    _dismiss = [dismiss copy];
    
    // 1.创建window
    _tempwindow = [[UIWindow alloc] init];
    _tempwindow.frame = [UIScreen mainScreen].bounds;
    _tempwindow.windowLevel = MAXFLOAT;
    _tempwindow.backgroundColor = [UIColor clearColor];
    
    // 2.创建一个蒙版
    UIButton *cover = [[UIButton alloc] init];
    cover.frame = [UIScreen mainScreen].bounds;
    cover.backgroundColor = [UIColor clearColor];
    [cover addTarget:self action:@selector(coverClick:) forControlEvents:UIControlEventTouchUpInside];
    [_tempwindow addSubview:cover];
    
    // 3.创建菜单
    UIImageView *menuView = [[UIImageView alloc] init];
    menuView.userInteractionEnabled = YES;
    menuView.image = [UIImage imageNamed:@"popover_background"];
    [menuView addSubview:contentView];
    [cover addSubview:menuView];
    
    // 4.设置菜单的frame
    // 4.1设置内容的xy(相当于设置间隙)
    contentView.x = 10;
    contentView.y = 15;
    // 4.2计算菜单的frame
    CGFloat menuViewW = CGRectGetMaxX(contentView.frame) + contentView.x;
    CGFloat menuViewH = CGRectGetMaxY(contentView.frame) + contentView.y;
    
    // 4.3转换坐标系, 将目标控件的坐标系转换为自定义window的坐标系
    CGRect resFrame = [_tempwindow convertRect:fromRect fromView:inView];
    
    CGFloat menuViewY = CGRectGetMaxY(resFrame);
    //  menuViewX = 目标控件最大的X - 目标控件宽度的一半 - 菜单宽度的一半
    CGFloat menuViewX = CGRectGetMaxX(resFrame) - (resFrame.size.width * 0.5) - menuViewW * 0.5;
    menuView.frame = CGRectMake(menuViewX, menuViewY, menuViewW, menuViewH);
    
    // 5.显示菜单
    _tempwindow.hidden = NO;
}

+ (void)coverClick:(UIButton *)cover{

    _tempwindow = nil;
    _viewController = nil;
    // 后续操作
    if (_dismiss != nil) {
        _dismiss();
    }
}


@end
